package com.cat.chapter037;

/**
 * @author cat
 * @description https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
 * @create 2025/6/18 18:51
 * @since JDK17
 */
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution01 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) {
            return root;
        }

        TreeNode l = lowestCommonAncestor(root.left, p, q);
        TreeNode r = lowestCommonAncestor(root.right, p, q);
        // 找节点的过程

        if (l != null && r != null) {
            return root;
        }

        if (l == null && r == null) {
            return null;
        }

        return l != null ? l : r;
    }
}
